/*
 * GerenciadordeSenhasView.java
 */
package gerenciadordesenhas;

import java.awt.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.EventObject;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.jdesktop.application.Application;
import java.util.Set;
import javax.crypto.spec.SecretKeySpec;

/**
 * The application's main frame.
 */
public class GerenciadordeSenhasView extends FrameView implements Application.ExitListener {

    public GerenciadordeSenhasView(SingleFrameApplication app) {
        super(app);

        initComponents();

        FileInputStream fis;

        ObjectInputStream ois = null;

        String[] cabecalho = {"Chave", "Senha"};
        String[][] senhas = new String[0][0];
        try {
            String location = this.getClassLocation(GerenciadordeSenhasView.class).getParent() + "/dado.dat";

            jLabel3.setText(location);

            fis = new FileInputStream(new File(location));
            ois = new ObjectInputStream(fis);
            container = (ContainerDados) ois.readObject();
            ois.close();

            senhas = getDados();

            TableModel model = new DefaultTableModel(senhas, cabecalho);
            jTable1.setModel(model);
        } catch (IOException ex) {
            container = new ContainerDados();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(GerenciadordeSenhasView.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            TableModel model = new DefaultTableModel(senhas, cabecalho);
            jTable1.setModel(model);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldChave = new javax.swing.JTextField();
        jTextFieldSenha = new javax.swing.JTextField();
        jButtonSalvar1 = new javax.swing.JButton();
        jButtonSalvar2 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();

        mainPanel.setName("mainPanel"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane1.setViewportView(jTable1);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(gerenciadordesenhas.GerenciadordeSenhasApp.class).getContext().getResourceMap(GerenciadordeSenhasView.class);
        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jTextFieldChave.setText(resourceMap.getString("jTextFieldChave.text")); // NOI18N
        jTextFieldChave.setName("jTextFieldChave"); // NOI18N

        jTextFieldSenha.setText(resourceMap.getString("jTextFieldSenha.text")); // NOI18N
        jTextFieldSenha.setName("jTextFieldSenha"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(gerenciadordesenhas.GerenciadordeSenhasApp.class).getContext().getActionMap(GerenciadordeSenhasView.class, this);
        jButtonSalvar1.setAction(actionMap.get("SalvarAction")); // NOI18N
        jButtonSalvar1.setText(resourceMap.getString("jButtonSalvar1.text")); // NOI18N
        jButtonSalvar1.setName("jButtonSalvar1"); // NOI18N

        jButtonSalvar2.setAction(actionMap.get("RemoverAction")); // NOI18N
        jButtonSalvar2.setText(resourceMap.getString("jButtonSalvar2.text")); // NOI18N
        jButtonSalvar2.setName("jButtonSalvar2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 538, Short.MAX_VALUE)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextFieldSenha, javax.swing.GroupLayout.DEFAULT_SIZE, 458, Short.MAX_VALUE)
                    .addComponent(jTextFieldChave, javax.swing.GroupLayout.DEFAULT_SIZE, 458, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButtonSalvar1, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButtonSalvar2, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 514, Short.MAX_VALUE)
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 245, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldChave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonSalvar1)
                    .addComponent(jButtonSalvar2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        setComponent(mainPanel);
    }// </editor-fold>//GEN-END:initComponents

    @Action
    public void SalvarAction() {
        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();

        if (encrypter == null) {
            SecretKeySpec desKey;
            String thekey = JOptionPane.showInputDialog("Qual é a senha de criptografia ?", "Senha simetrica de acesso");
            if (thekey != null && (!"".equals(thekey))) {
                if (thekey.length() >= 0) {
                    desKey = DesEncrypter.obtemSenha(thekey);
                    encrypter = new DesEncrypter(desKey);
                } else {
                    JOptionPane.showMessageDialog(null, "A senha tem de ter no minimo oito caracteres !");
                }
            }
        }

        Dado d = new Dado();
        d.setChave(jTextFieldChave.getText());
        d.setSenha(encrypter.encrypt(jTextFieldSenha.getText()));

        modelo.addRow(new String[]{d.getChave(), jTextFieldSenha.getText()});

        container.addDado(d);

        jTextFieldChave.setText("");
        jTextFieldSenha.setText("");

    }

    @Action
    public void RemoverAction() {
        int row = jTable1.getSelectedRow();

        if (row >= 0) {
            DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
            container.removeDado((String) modelo.getValueAt(row, 0));
            modelo.removeRow(row);
        }

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonSalvar1;
    private javax.swing.JButton jButtonSalvar2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextFieldChave;
    private javax.swing.JTextField jTextFieldSenha;
    private javax.swing.JPanel mainPanel;
    // End of variables declaration//GEN-END:variables
    private ContainerDados container;
    private DesEncrypter encrypter;

    public boolean canExit(EventObject e) {
        Object source = (e != null) ? e.getSource() : null;
        Component owner = (source instanceof Component) ? (Component) source : null;
        int option = JOptionPane.showConfirmDialog(owner, "Deseja realmente sair do sistema?", "Saindo", JOptionPane.YES_NO_OPTION);
        return option == JOptionPane.YES_OPTION;
    }

    public void willExit(EventObject arg0) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(new File(jLabel3.getText()));
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(container);
            container = null;
            oos.close();
        } catch (IOException ex) {
            Logger.getLogger(GerenciadordeSenhasView.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    protected String[][] getDados() {
        SecretKeySpec desKey;
        String thekey = JOptionPane.showInputDialog("Qual é a senha de criptografia ?", "Senha simetrica de acesso");
        if (thekey != null && (!"".equals(thekey))) {
            desKey = DesEncrypter.obtemSenha(thekey);
            encrypter = new DesEncrypter(desKey);

            Map<String, String> mapa = container.getMap();
            String[][] a = new String[mapa.size()][2];
            Set<String> set = mapa.keySet();
            Iterator<String> it = set.iterator();
            int count = 0;
            while (it.hasNext()) {
                String e = it.next();
                String v = mapa.get(e);
                a[count][0] = e;
                a[count][1] = encrypter.decrypt(v);
                count++;
            }
            return a;
        } else {
            System.exit(0);
        }
        return null;
    }

    public File getClassLocation(Class c) throws IOException, FileNotFoundException {
        if (c == null) {
            throw new NullPointerException();
        }

        String className = c.getName();
        String resourceName = className.replace('.', '/') + ".class";
        ClassLoader classLoader = c.getClassLoader();
        if (classLoader == null) {
            classLoader = ClassLoader.getSystemClassLoader();
        }
        URL url = classLoader.getResource(resourceName);

        String szUrl = url.toString();
        if (szUrl.startsWith("jar:file:")) {
            try {
                szUrl = szUrl.substring("jar:".length(), szUrl.lastIndexOf("!"));
                URI uri = new URI(szUrl);
                return new File(uri);
            } catch (URISyntaxException e) {
                throw new IOException(e.toString());
            }
        } else if (szUrl.startsWith("file:")) {
            try {
                szUrl = szUrl.substring(0, szUrl.length() - resourceName.length());
                URI uri = new URI(szUrl);
                return new File(uri);
            } catch (URISyntaxException e) {
                throw new IOException(e.toString());
            }
        }

        throw new FileNotFoundException(szUrl);
    }
}
